package cn.nubia.admin.common.utils;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jason on 2015/6/27.
 */
public class BeanUtils {
    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 将bean转换成map格式
     * @param bean
     * @return
     */
    public static Map<String, Object> convertBeanToMap(Object bean) {
        Field[] fields = bean.getClass().getDeclaredFields() ;
        Map<String, Object> map = new HashMap<>() ;
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (field.get(bean) != null) {
                    map.put(field.getName(), field.get(bean)) ;
                }
            } catch (IllegalAccessException e) {
                logger.error("bean to map has error,the property is " + field.getName());
            }
        }
        return map ;
    }
    /**
     * 复制属性.
     *
     * @param orig
     * @param dest
     */
    public static void copyProperties(Object orig, Object dest) {
        try {
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
